#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
使用示例：如何在登录后调用接口并获取authorization
"""

import requests
import yaml
import os

def get_authorization_from_login():
    """方法1：通过登录获取authorization"""
    login_url = "https://xuntian-cloud-test3.tclpv.com/api/auth/login"
    payload = {
        "username": "kt_wuzex",
        "password": "tcl123",
        "type": 1,
        "from": "xts-new"
    }
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"
    }
    
    response = requests.post(login_url, json=payload, headers=headers)
    data = response.json()
    token = data["token"]
    
    # 构造authorization头
    authorization = f"Bearer {token}"
    print(f"获取到的authorization: {authorization}")
    return authorization

def call_api_with_authorization(authorization, endpoint="/api/user/info"):
    """方法2：使用authorization调用接口"""
    base_url = "https://xuntian-cloud-test3.tclpv.com"
    url = f"{base_url}{endpoint}"
    
    headers = {
        "Authorization": authorization,
        "Content-Type": "application/json",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36"
    }
    
    response = requests.get(url, headers=headers)
    print(f"接口调用成功，状态码: {response.status_code}")
    print(f"使用的authorization: {authorization}")
    print(f"响应内容: {response.json()}")
    return response.json()

def save_authorization_to_file(authorization, filename="authorization.txt"):
    """方法3：保存authorization到文件"""
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(authorization)
    print(f"authorization已保存到 {filename}")

def load_authorization_from_file(filename="authorization.txt"):
    """方法4：从文件加载authorization"""
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as f:
            authorization = f.read().strip()
        print(f"从 {filename} 加载了authorization: {authorization}")
        return authorization
    return None

def main():
    print("=== 演示如何获取和使用authorization ===\n")
    
    # 1. 登录获取authorization
    print("1. 登录获取authorization...")
    authorization = get_authorization_from_login()
    print()
    
    # 2. 使用authorization调用接口
    print("2. 使用authorization调用接口...")
    call_api_with_authorization(authorization)
    print()
    
    # 3. 保存authorization到文件
    print("3. 保存authorization到文件...")
    save_authorization_to_file(authorization)
    print()
    
    # 4. 从文件加载authorization并调用接口
    print("4. 从文件加载authorization并调用接口...")
    loaded_auth = load_authorization_from_file()
    if loaded_auth:
        call_api_with_authorization(loaded_auth, "/api/user/info")
    print()
    
    print("=== 演示完成 ===")

if __name__ == "__main__":
    main() 